<?php
namespace Api\Controller;
use Api\Controller\CommonController;
class CallbackController extends CommonController {
	private $isError=1;  //支付是否错误
	
	private $payResultCode;
	private $paygatewayOrderNo;
	private $orderNo;
	private $amount;
	private $payTime;
	
	public function _initialize(){
		parent::_initialize();
	}
	
	/*public function test(){
		$result=$this->_loginPassword("18664699093","f0f5f3bdc5bf95e3ad6d6f5e8920338e");
		var_dump($result);
		exit;
	}*/
	
	/**
	 *  汇通“在线支付”回调接口
	 */
	public function notify(){
		$this->payResultCode = $_REQUEST['payResultCode'];
		$this->paygatewayOrderNo = $_REQUEST['paygatewayOrderNo'];
		$this->orderNo = $_REQUEST['orderNo'];
		$this->amount = $_REQUEST['amount'];
		$this->payTime = $_REQUEST['payTime'];
		
		if($this->payResultCode == 'S')
		{
			//判断订单是否存在
			$order=D("Order")->getOrder("",array("orderSn"=>$this->orderNo,"isOn"=>1));
			if (!$order) {
				$this->msg = "notifyurl：订单不存在，应退款 ".$this->amount."，支付流水号：".$this->paygatewayOrderNo."订单号：".$this->orderNo;
				$this->payLog();exit;
			}	
				
			//判断是否重复支付
			if($order['status']==1)
			{
				$this->msg = "notifyurl：订单重复支付，应退款 ".$this->amount."，支付流水号：".$this->paygatewayOrderNo;
				$this->payLog();exit;
			}
	
			//验证支付金额
			$orderAmount = $order['payPrice'];
			if($orderAmount != $this->amount)
			{
				$this->msg = "notifyurl：支付金额不匹配，应支付金额：".$orderAmount."，实际支付金额：".$this->amount."，支付流水号：".$this->paygatewayOrderNo;
				$this->payLog();exit;
			}
			
			//更新订单信息
			$orderUpdateData=[
					"orderID"=>$order['orderID'],
					"status"=>1,"payTime"=>time(),
					"payModeID"=>2,
					"payModeName"=>"在线支付",
					"updateTime"=>time(),
					'logisticsStatus'=>$logisticsStatus
			];
			$update=D("Order")->updateOrder($orderUpdateData);
				
			if(!$update){
				$this->msg = "notifyurl：订单支付成功，更新订单状态失败，应退款 ".$this->amount."，支付流水号：".$this->paygatewayOrderNo;
				$this->payLog();exit;
			}
			
			D()->startTrans();
			
			//获取订单商品信息
			//$orderGoods=D("OrderGoods")->getOrderGoodsList(1,1000,array("orderID"=>$order['orderID'],"status"=>0));
			$orderGoods=M('OrderGoods a')
			->field('a.goodsID,a.apiOrderSn,a.phone,a.shopID,a.num,b.code')
			->join(C('DB_PREFIX').'goods_cat b on a.catID=b.catID','LEFT')
			->where(["a.orderID"=>$order['orderID'],"status"=>0])
			->select();

			if(!$orderGoods){
				D()->rollback();
				$this->msg = "notifyurl：更新订单状态失败，应退款 ".$this->amount."，支付流水号：".$this->paygatewayOrderNo;
				$this->payLog();exit;
			}
			
			
			/* if($order['orderType']=="1"){
			    foreach ($orderGoods as $a){
			        $shopID=D("Goods")->where(array("goodsID"=>$a['goodsID']))->getField("shopID");
			        $shop=D("Shop")->field("province,city")->where(array("shopID"=>$shopID))->find();
			        
			        //通过接口确认订单(确认预下单)
			        $result=$this->_confirmCouponOrder($a['apiOrderSn'],$a['phone'],$this->_getAreaNum($shop['province'],$shop['city']));
			        if (!$result) {
			            D()->rollback();
			            $this->msg = "notifyurl：1接口确认订单状态失败，应退款 ".$this->amount."，支付流水号：".$this->paygatewayOrderNo;
			            $this->payLog();exit;
			        }
			    
			        foreach ($result['subList'] as $b){
			            $orderCodeData=array(
			                "orderID"=>$order['orderID'],
			                "goodsID"=>$a['goodsID'],
			                "orderSn"=>$order['orderSn'],
			                "apiOrderSn"=>$a['apiOrderSn'],
			                "username"=>$b['username'],
			                "couponName"=>$b['couponName'],
			                "assisCode"=>$b['assisCode'],
			                "couponCode"=>$b['couponCode'],
			                "endTime"=>$b['endTime'],
			                "mobile"=>$b['mobile'],
			                "parPrice"=>$b['parPrice'],
			                "addTime"=>time(),
			            );
			            $addOrderCode=D("OrderCode")->data($orderCodeData)->add();
			            if (!$addOrderCode) {
			                D()->rollback();
			                $this->msg = "notifyurl：2接口确认订单状态失败，应退款 ".$this->amount."，支付流水号：".$this->paygatewayOrderNo;
			                $this->payLog();exit;
			            }
			        }
			    
			        
			    }
			} */
			
			$logisticsStatus=0;
			foreach ($orderGoods as $a){
				//$shopID=D("Goods")->where(array("goodsID"=>$a['goodsID']))->getField("shopID");
				$shop=D("Shop")->field("province,city")->where(array("shopID"=>$a['shopID']))->find();
				
				if(!empty($a['code'])){
					//通过接口确认订单(确认预下单)
					if($a['code']!="virtualCode"){
						$result=$this->_confirmCouponOrder($a['apiOrderSn'],$a['phone'],$this->_getAreaNum($shop['province'],$shop['city']));
						$this->msg = "预下单成功，订单编号：". $this->orderNo . "。用户id：".$order['userID']."，发码电话：".$a['phone'];
					} else {
						$result = true;
					}
					
					$this->payLog();
					if (!$result) {
						D()->rollback();
						//$this->msg = "notifyurl：1接口确认订单状态失败，应退款 ".$this->amount."，支付流水号：".$this->paygatewayOrderNo;
						$this->msg = "确认预下单失败，支付流水号：". $this->paygatewayOrderNo . "。接口返回错误代码为".$this->apiErrorCode."，错误信息为".$this->apiErrorMsg;
						$this->payLog();exit;
					}
					$logisticsStatus=1;
					foreach ($result['subList'] as $b){
						$orderCodeData=array(
								"orderID"=>$order['orderID'],
								"goodsID"=>$a['goodsID'],
								"orderSn"=>$order['orderSn'],
								"apiOrderSn"=>$a['apiOrderSn'],
								"username"=>$b['username'],
								"couponName"=>$b['couponName'],
								"assisCode"=>$b['assisCode'],
								"couponCode"=>$b['couponCode'],
								"endTime"=>$b['endTime'],
								"mobile"=>$b['mobile'],
								"parPrice"=>$b['parPrice'],
								"addTime"=>time(),
						);
						$addOrderCode=D("OrderCode")->data($orderCodeData)->add();
						if (!$addOrderCode) {
							D()->rollback();
							$this->msg = "notifyurl：2接口确认订单状态失败，应退款 ".$this->amount."，支付流水号：".$this->paygatewayOrderNo;
							$this->payLog();exit;
						}
					}
				}
			}
			
			$orderGoodsData=array(
					"status"=>1,
					"updateTime"=>time()
			);
			$updateGoods=D("OrderGoods")->where(array('orderID'=>$order['orderID']))->save($orderGoodsData);
			if (!$updateGoods) {
				D()->rollback();
				$this->msg = "notifyurl：3接口确认订单状态失败，应退款 ".$this->amount."，支付流水号：".$this->paygatewayOrderNo;
				$this->payLog();exit;
			}
			
			foreach($orderGoods as $ugoods){
				$updateGoods=D('goods')->where(['goodsID'=>$ugoods['goodsID']])->setInc('saleNum',$ugoods['num']);
				$updateGoods=D('goods')->where(['goodsID'=>$ugoods['goodsID']])->setDec('restNum',$ugoods['num']);
				if (!$updateGoods) {
					D()->rollback();
					$this->msg = "notifyurl：4接口确认订单状态失败，应退款 ".$this->amount."，支付流水号：".$this->paygatewayOrderNo;
					$this->payLog();exit;
				}
			}
			
			
			
			D()->commit();
			$this->msg = "notifyurl：订单支付成功！";
			$this->isError=0;
			$this->payLog();
			
			echo '<?xml version=\"1.0\" encoding=\"UTF-8\"?><result>1</result>';
			exit;
			
		}
		elseif($this->payResultCode == 'F')
		{
			$this->msg = "returnurl：支付失败，支付流水号：".$this->paygatewayOrderNo."，商户订单号：".$this->orderNo;
			$this->payLog();exit;
		}
		else
		{
			$this->msg = "returnurl：支付失败，支付流水号：".$this->paygatewayOrderNo."，商户订单号：".$this->orderNo;
			$this->payLog();exit;
			
		}
	}
	
	private function payLog(){
		$data=array(
				"payResultCode"=>$this->payResultCode,
				"paygatewayOrderNo"=>$this->paygatewayOrderNo,
				"orderNo"=>$this->orderNo,
				"amount"=>$this->amount,
				"payTime"=>$this->payTime,
				"isError"=>$this->isError,
				"msg"=>$this->msg,
				"addTime"=>time()
		);
		file_put_contents("payLog/".date("Ymd")."txt", json_encode($data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
		M("PayLog")->data($data)->add();
	}
}